package cn.jnetty.ioc.executer.pool;

import cn.jnetty.ioc.executer.JnettyWorkerImpl;
import cn.jnetty.remoting.JnettyThreadFactory;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/4/6 18:30
 * 描述：
 */
public class JnettyRunnablePool {
	/**
	 * worker线程数组
	 */
	private final AtomicInteger workerIndex = new AtomicInteger();
	private JnettyWorker[] workeres;
	public JnettyRunnablePool(Executor worker, int threadCount) {
		int cout = threadCount == 0 ? Runtime.getRuntime().availableProcessors() * 2 : threadCount;
		initWorker(worker, cout);
	}
	/**
	 * 初始化worker线程
	 * @param worker
	 * @param count
	 */
	private void initWorker(Executor worker, int count) {
		if(worker == null){
			worker = new ThreadPoolExecutor(count,count,60L, TimeUnit.SECONDS,new LinkedBlockingQueue<>(),new JnettyThreadFactory("jnetty-handler-"));
		}
		this.workeres = new JnettyWorkerImpl[count];
		for (int i = 0; i < workeres.length; i++) {
			workeres[i] = new JnettyWorkerImpl(worker, "worker thread " + (i+1), this);
		}
	}
	/**
	 * 获取一个worker
	 * @return
	 */
	public JnettyWorker nextWorker() {
		 return workeres[Math.abs(workerIndex.getAndIncrement() % workeres.length)];
	}
	public JnettyWorker[] getWorkeres(){
		return workeres;
	}
}